<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>运费计算器 - 基础计算</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        .card-hover { transition: transform 0.3s ease, box-shadow 0.3s ease; }
        .card-hover:hover { transform: translateY(-5px); box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); }
        .fade-in { animation: fadeIn 0.5s ease-in-out; }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
    </style>
</head>
<body class="bg-gray-50 min-h-screen font-sans">
    <!-- 顶部导航栏 -->
    <header class="bg-blue-600 text-white shadow-md">
        <div class="container mx-auto px-4 py-6">
            <h1 class="text-3xl font-bold flex items-center">
                <i class="fa fa-truck mr-3"></i>运费计算器
            </h1>
            <p class="mt-2 opacity-90">快速计算不同地区的运费，支持多种计费方式</p>
        </div>
    </header>

    <!-- 功能导航 -->
    <nav class="bg-white shadow-sm">
        <div class="container mx-auto px-4">
            <div class="flex overflow-x-auto py-4 space-x-6 md:space-x-8 whitespace-nowrap">
                <a href="/" class="text-blue-600 font-medium border-b-2 border-blue-600 pb-2 flex items-center">
                    <i class="fa fa-calculator mr-2"></i>基础计算
                </a>
                <a href="/manage" class="text-gray-600 hover:text-blue-600 transition-colors flex items-center">
                    <i class="fa fa-sliders mr-2"></i>费率维护
                </a>
                <a href="/excel" class="text-gray-600 hover:text-blue-600 transition-colors flex items-center">
                    <i class="fa fa-file-excel-o mr-2"></i>批量测算
                </a>
            </div>
        </div>
    </nav>

    <!-- 主要内容区 -->
    <main class="container mx-auto px-4 py-8">
        <div class="max-w-4xl mx-auto">
            <!-- 计算卡片 -->
            <div class="bg-white rounded-lg shadow-md p-6 md:p-8 mb-8 fade-in card-hover">
                <h2 class="text-2xl font-bold text-gray-800 mb-6">基础运费计算</h2>
                
                <form id="calculatorForm" class="space-y-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label for="provinceSelect" class="block text-sm font-medium text-gray-700 mb-1">
                                选择省份 <span class="text-red-500">*</span>
                            </label>
                            <select 
                                id="provinceSelect" 
                                class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-150 ease-in-out"
                            >
                                <option value="">-- 加载中，请稍候 --</option>
                            </select>
                            <div id="provinceError" class="text-red-500 text-xs mt-1 hidden">请选择省份</div>
                        </div>
                        
                        <div>
                            <label for="weightInput" class="block text-sm font-medium text-gray-700 mb-1">
                                重量（kg）<span class="text-red-500">*</span>
                            </label>
                            <input 
                                type="number" 
                                id="weightInput" 
                                step="0.1" 
                                min="0" 
                                class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-150 ease-in-out"
                                placeholder="请输入重量，例如：2.5"
                            >
                            <div id="weightError" class="text-red-500 text-xs mt-1 hidden">请输入有效的重量（非负数）</div>
                        </div>
                        
                        <div>
                            <label for="pieceCountInput" class="block text-sm font-medium text-gray-700 mb-1">
                                件数
                            </label>
                            <input 
                                type="number" 
                                id="pieceCountInput" 
                                min="1" 
                                value="1" 
                                class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-150 ease-in-out"
                                placeholder="默认为1件"
                            >
                            <div id="pieceError" class="text-red-500 text-xs mt-1 hidden">请输入有效的件数（至少1件）</div>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                计费方式
                            </label>
                            <div id="calcTypeDisplay" class="w-full px-4 py-2 border border-gray-300 rounded-md bg-gray-50 text-gray-500">
                                请先选择省份
                            </div>
                        </div>
                    </div>
                    
                    <div class="pt-2">
                        <button 
                            type="submit" 
                            class="w-full md:w-auto px-6 py-3 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition duration-150 ease-in-out font-medium"
                        >
                            <i class="fa fa-calculator mr-2"></i>计算运费
                        </button>
                    </div>
                </form>
            </div>
            
            <!-- 结果展示区 -->
            <div id="resultSection" class="hidden fade-in">
                <div class="bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-lg shadow-md p-6 md:p-8 mb-8">
                    <h3 class="text-xl font-bold mb-4 flex items-center">
                        <i class="fa fa-check-circle mr-2"></i>计算结果
                    </h3>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <p class="text-blue-100 text-sm mb-1">省份</p>
                            <p id="resultProvince" class="text-2xl font-medium"></p>
                        </div>
                        
                        <div>
                            <p class="text-blue-100 text-sm mb-1">重量</p>
                            <p id="resultWeight" class="text-2xl font-medium"></p>
                        </div>
                        
                        <div>
                            <p class="text-blue-100 text-sm mb-1">件数</p>
                            <p id="resultPieceCount" class="text-2xl font-medium"></p>
                        </div>
                        
                        <div>
                            <p class="text-blue-100 text-sm mb-1">计费方式</p>
                            <p id="resultCalcType" class="text-2xl font-medium"></p>
                        </div>
                    </div>
                    
                    <div class="mt-8 pt-6 border-t border-blue-400/50 text-center">
                        <p class="text-blue-100 text-lg mb-2">应付运费</p>
                        <p id="resultFreight" class="text-4xl font-bold"></p>
                    </div>
                </div>
            </div>
            
            <!-- 计费说明 -->
            <div class="bg-white rounded-lg shadow-md p-6 mb-8 fade-in">
                <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                    <i class="fa fa-info-circle text-blue-500 mr-2"></i>计费说明
                </h3>
                
                <div class="space-y-4 text-gray-700">
                    <div>
                        <h4 class="font-medium text-blue-600">1. 重量阶梯计费</h4>
                        <p class="text-sm mt-1">根据不同重量段收取不同费率，例如：0-1kg 10元，1-2kg 8元，2kg以上5元/kg。</p>
                    </div>
                    
                    <div>
                        <h4 class="font-medium text-blue-600">2. 固定续重计费</h4>
                        <p class="text-sm mt-1">首重（如1kg）收取固定费用，超出部分按续重费率计算，例如：首重1kg 10元，续重每kg 5元。</p>
                    </div>
                    
                    <div>
                        <h4 class="font-medium text-blue-600">3. 按件计费</h4>
                        <p class="text-sm mt-1">与重量无关，按件数收费，例如：每件3元，5件共计15元。</p>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-gray-800 text-white mt-16">
        <div class="container mx-auto px-4 py-8">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <p class="text-sm opacity-75">© 2024 运费计算器</p>
                    <p class="text-xs opacity-50 mt-1">高效、准确的运费计算工具</p>
                </div>
                <div class="flex space-x-6">
                    <a href="#" class="text-sm opacity-75 hover:opacity-100 transition-opacity">使用帮助</a>
                    <a href="#" class="text-sm opacity-75 hover:opacity-100 transition-opacity">关于我们</a>
                </div>
            </div>
        </div>
    </footer>

    <script>
        // DOM元素
        const provinceSelect = document.getElementById('provinceSelect');
        const weightInput = document.getElementById('weightInput');
        const pieceCountInput = document.getElementById('pieceCountInput');
        const calcTypeDisplay = document.getElementById('calcTypeDisplay');
        const calculatorForm = document.getElementById('calculatorForm');
        const resultSection = document.getElementById('resultSection');
        const provinceError = document.getElementById('provinceError');
        const weightError = document.getElementById('weightError');
        const pieceError = document.getElementById('pieceError');
        
        // 省份数据缓存
        let provincesData = [];
        
        // 页面加载时获取省份列表
        document.addEventListener('DOMContentLoaded', () => {
            fetchProvinces();
            
            // 省份选择变化时更新计费方式显示
            provinceSelect.addEventListener('change', updateCalcTypeDisplay);
        });
        
        // 获取省份列表
        async function fetchProvinces() {
            try {
                const response = await fetch('/api/provinces');
                const result = await response.json();
                
                if (result.success && Array.isArray(result.data) && result.data.length > 0) {
                    provincesData = result.data;
                    renderProvinceOptions();
                } else {
                    provinceSelect.innerHTML = '<option value="">暂无省份数据，请先配置费率</option>';
                }
            } catch (err) {
                console.error('获取省份列表失败:', err);
                provinceSelect.innerHTML = '<option value="">获取省份失败，请刷新页面重试</option>';
            }
        }
        
        // 渲染省份下拉选项
        function renderProvinceOptions() {
            let options = '<option value="">-- 请选择省份 --</option>';
            
            provincesData.forEach(province => {
                options += `<option value="${province.id}" data-calc-type="${province.calc_type}">${province.name}</option>`;
            });
            
            provinceSelect.innerHTML = options;
        }
        
        // 更新计费方式显示
        function updateCalcTypeDisplay() {
            const selectedOption = provinceSelect.options[provinceSelect.selectedIndex];
            const calcType = selectedOption ? selectedOption.getAttribute('data-calc-type') : '';
            
            if (calcType) {
                let calcTypeName = '';
                switch (calcType) {
                    case 'weight_step':
                        calcTypeName = '重量阶梯计费';
                        break;
                    case 'fixed_add':
                        calcTypeName = '固定续重计费';
                        break;
                    case 'piece':
                        calcTypeName = '按件计费';
                        break;
                    default:
                        calcTypeName = '未知计费方式';
                }
                calcTypeDisplay.textContent = calcTypeName;
                calcTypeDisplay.classList.remove('bg-gray-50', 'text-gray-500');
            } else {
                calcTypeDisplay.textContent = '请先选择省份';
                calcTypeDisplay.classList.add('bg-gray-50', 'text-gray-500');
            }
        }
        
        // 表单提交处理
        calculatorForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            // 验证表单
            if (!validateForm()) {
                return;
            }
            
            try {
                const provinceId = provinceSelect.value;
                const weight = parseFloat(weightInput.value);
                const pieceCount = parseInt(pieceCountInput.value);
                
                // 发送计算请求
                const response = await fetch('/api/provinces/calculate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        provinceId,
                        weight,
                        pieceCount
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // 显示计算结果
                    displayResult(result.data);
                } else {
                    alert(`计算失败: ${result.error}`);
                }
            } catch (err) {
                console.error('计算运费失败:', err);
                alert('计算失败，请重试');
            }
        });
        
        // 表单验证
        function validateForm() {
            let isValid = true;
            const provinceId = provinceSelect.value;
            const weight = weightInput.value.trim();
            const pieceCount = pieceCountInput.value.trim();
            
            // 验证省份
            if (!provinceId) {
                provinceError.classList.remove('hidden');
                isValid = false;
            } else {
                provinceError.classList.add('hidden');
            }
            
            // 验证重量
            if (!weight || isNaN(parseFloat(weight)) || parseFloat(weight) < 0) {
                weightError.classList.remove('hidden');
                isValid = false;
            } else {
                weightError.classList.add('hidden');
            }
            
            // 验证件数
            if (!pieceCount || isNaN(parseInt(pieceCount)) || parseInt(pieceCount) < 1) {
                pieceError.classList.remove('hidden');
                isValid = false;
            } else {
                pieceError.classList.add('hidden');
            }
            
            return isValid;
        }
        
        // 显示计算结果
        function displayResult(data) {
            // 转换计费方式为中文
            let calcTypeName = '';
            switch (data.calcType) {
                case 'weight_step':
                    calcTypeName = '重量阶梯计费';
                    break;
                case 'fixed_add':
                    calcTypeName = '固定续重计费';
                    break;
                case 'piece':
                    calcTypeName = '按件计费';
                    break;
                default:
                    calcTypeName = data.calcType;
            }
            
            // 填充结果数据
            document.getElementById('resultProvince').textContent = data.province;
            document.getElementById('resultWeight').textContent = `${data.weight} kg`;
            document.getElementById('resultPieceCount').textContent = `${data.pieceCount} 件`;
            document.getElementById('resultCalcType').textContent = calcTypeName;
            document.getElementById('resultFreight').textContent = `¥ ${data.freight.toFixed(2)}`;
            
            // 显示结果区域
            resultSection.classList.remove('hidden');
            
            // 滚动到结果区域
            resultSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    </script>
</body>
</html>
